package org.orr.budgetpro.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.orr.budgetpro.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserDAO {
	@Autowired
	private SessionFactory sessionFactory;

	public User getUser(String userId) {
		return (User) sessionFactory.getCurrentSession()
				.get(User.class, userId);
	}

	public void saveUser(User user) {
		Session session = sessionFactory.getCurrentSession();

		if (userIdExists(user.getUserId())) {
			// If user exists in database, update it
			session.merge(user);
		} else {
			// Otherwise, user doesn't exist, so save/insert it
			session.save(user);
		}
	}

	public boolean userIdExists(String userId) {
		Session session = sessionFactory.getCurrentSession();
		List matchingIds = session
				.createQuery("select userId from User as u where u.userId = ?")
				.setString(0, userId).list();
		return matchingIds.size() > 0;
	}
}
